﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Chowpoo.Util;
using CourseSystem.Core.BLL;
using log4net;

namespace CourseSystem.Common.Helpers
{
    public class ResourcesHelper
    {
        private static readonly List<SelectListItem> TextTypeSelectList;
        private static readonly List<SelectListItem> TextTypeSelectListWithDef;
        public static readonly string UploadImgExt;
        public static readonly string UploadTextExt;
        public static readonly string UploadLinkExt;
        public static readonly string UploadSoundExt;
        public static readonly string UploadVideoExt;
        public static readonly string UploadFlashExt;
        public static readonly string UploadPPTExt;
        public static readonly int UploadImgSize;
        public static readonly int UploadTextSize;
        public static readonly int UploadLinkSize;
        public static readonly int UploadSoundSize;
        public static readonly int UploadVideoSize;
        public static readonly int UploadFlashSize;
        public static readonly int UploadPPTSize;

        private const string FlashHtml = "<embed height=\"400\" type=\"application/x-shockwave-flash\" width=\"480\" src=\"{0}\" allowfullscreen=\"true\" loop=\"true\" play=\"true\" menu=\"false\" quality=\"high\" wmode=\"opaque\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000\" />";

        private const string VideoHtml = "<embed height=\"400\" type=\"application/x-mplayer2\" width=\"480\" src=\"{0}\" autostart=\"false\" enablecontextmenu=\"false\" classid=\"clsid:6bf52a52-394a-11d3-b153-00c04f79faa6\" />";

        private const string SoundHtml = "<embed height=\"400\" type=\"application/x-mplayer2\" width=\"480\" src=\"{0}\" autostart=\"false\" enablecontextmenu=\"false\" classid=\"clsid:6bf52a52-394a-11d3-b153-00c04f79faa6\" />";

        private const string ImgHtml = "<img alt=\"\" src=\"{0}\" width=\"{1}\" />";

        private const string DownHtml = "<a href=\"{0}\" target=\"_blank\" >下载</a>";
        private static readonly ILog Log = LogManager.GetLogger(typeof (ResourcesHelper));
        static ResourcesHelper()
        {
            TextTypeSelectList = new List<SelectListItem>
                                     {
                                         new SelectListItem {Text = "教师上传", Value = "1"},
                                         new SelectListItem {Text = "学生上传", Value = "2"},
                                     };
            TextTypeSelectListWithDef = new List<SelectListItem>
                                     {
                                         new SelectListItem { Text = "全部", Value = "0" },
                                         new SelectListItem {Text = "教师上传", Value = "1"},
                                         new SelectListItem {Text = "学生上传", Value = "2"},
                                     };
            UploadFlashExt = ConfigurationManager.AppSettings["UploadFlashExt"];
            UploadImgExt = ConfigurationManager.AppSettings["UploadImgExt"];
            UploadTextExt = ConfigurationManager.AppSettings["UploadTextExt"];
            UploadLinkExt = ConfigurationManager.AppSettings["UploadLinkExt"];
            UploadSoundExt = ConfigurationManager.AppSettings["UploadSoundExt"];
            UploadVideoExt = ConfigurationManager.AppSettings["UploadVideoExt"];
            UploadPPTExt = ConfigurationManager.AppSettings["UploadPPTExt"];
            UploadImgSize = ConfigurationManager.AppSettings["UploadImgSize"].CheckInt(10000);
            UploadTextSize = ConfigurationManager.AppSettings["UploadTextSize"].CheckInt(10000);
            UploadLinkSize = ConfigurationManager.AppSettings["UploadLinkSize"].CheckInt(10000);
            UploadSoundSize = ConfigurationManager.AppSettings["UploadSoundSize"].CheckInt(10000);
            UploadVideoSize = ConfigurationManager.AppSettings["UploadVideoSize"].CheckInt(10000);
            UploadFlashSize = ConfigurationManager.AppSettings["UploadFlashSize"].CheckInt(10000);
            UploadPPTSize = ConfigurationManager.AppSettings["UploadPPTSize"].CheckInt(10000);
        }

        public static List<SelectListItem> GetTextType(bool isNeedAll = false)
        {
            var re = TextTypeSelectList;
            if (isNeedAll)
                return TextTypeSelectListWithDef;
            return re;
        }

        public static string GetHtml(string fileName, byte type)
        {
            if (string.IsNullOrEmpty(fileName))
                return "";
            var dofileName = CommonHelper.Domain + fileName;
            switch (type)
            {

                case 2:
                    var img = Image.FromFile(HttpContext.Current.Server.MapPath("~/") + fileName);
                    return string.Format(ImgHtml, dofileName, img.Width > 480 ? 480 : img.Width);
                case 3:
                    return string.Format(FlashHtml, dofileName);
                case 4:
                    return string.Format(SoundHtml, dofileName);
                case 5:
                    return string.Format(VideoHtml, dofileName);
                default:
                    return string.Format(DownHtml, dofileName);
            }
        }

        public static string GetTextByType(byte type)
        {
            if (type == 0)
                return "全部";
            return TextTypeSelectList[type - 1].Text;
        }
        public static string UploadSoftware(HttpPostedFileBase file, out string msg, bool isNeed = false)
        {
            msg = "";
            if (isNeed && (file == null || file.ContentLength == 0))
            {
                msg = "请选择文件上传";
                return "";
            }
            if (file == null || file.ContentLength == 0)
                return "";
            string testExt = GetFileExt(file.FileName);
            if (string.IsNullOrEmpty(testExt))
            {
                msg = "后缀名获取失败!";
                return "";
            }
            if (testExt != "rar")
            {
                msg = "上传格式必须为:rar压缩包";
                return "";
            }
            var ext = "." + testExt;
            if (!IsMatchSize(file, 200000))
            {
                msg = "不能上传超过" + 200000 + "K的文件.";
                return "";
            }
            string filePath = HttpContext.Current.Server.MapPath("~/Upload/Software/");
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            string tempSrc = DateTime.Now.ToString("yyyyMMddHHssfff") + ext;
            var fileName = filePath + tempSrc;
            file.SaveAs(fileName);
            return "Upload/Software/" + tempSrc;
        }
        public static string UploadCourseware(HttpPostedFileBase file, string fileDic, out string msg, bool isNeed = false)
        {
            msg = "";
            if (isNeed && (file == null || file.ContentLength == 0))
            {
                msg = "请选择文件上传";
                return "";
            }
            if (file == null || file.ContentLength == 0)
                return "";
            string testExt = GetFileExt(file.FileName);
            if (string.IsNullOrEmpty(testExt))
            {
                msg = "后缀名获取失败!";
                return "";
            }

            if (!IsMatchSize(file, 10000))
            {
                msg = "不能上传超过" + 10000 + "K的文件.";
                return "";
            }
            string filePath = HttpContext.Current.Server.MapPath("~/Upload/Courseware/");
            string time = fileDic;
            Log.Error(time);
            if (string.IsNullOrEmpty(time))
            {
                time = DateTime.Now.ToString("yyyyMMddhhmmssfff");
            }
            time = time + '/';

            Log.Error(filePath + time);
            if (!Directory.Exists(filePath + time))
                Directory.CreateDirectory(filePath + time);

            string tempSrc = file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1);
            var fileName = filePath + time + tempSrc;
            file.SaveAs(fileName);
            return time + tempSrc;

        }

        public static string UploadFile(HttpPostedFileBase file, byte type, out string msg, bool isNeed = false)
        {
            msg = "";
            if (isNeed && (file == null || file.ContentLength == 0))
            {
                msg = "请选择文件上传";
                return "";
            }
            switch (type)
            {
                case 1:
                    return SaveFile(GetTypeByEn(type), file, UploadTextExt, UploadTextSize, out msg);
                case 2:
                    return ImgHelper.UploadImg(file, UploadImgSize, 0, 0, out msg);
                case 3:
                    return SaveFile(GetTypeByEn(type), file, UploadFlashExt, UploadFlashSize, out msg);
                case 4:
                    return SaveFile(GetTypeByEn(type), file, UploadSoundExt, UploadFlashSize, out msg);
                case 5:
                    return SaveFile(GetTypeByEn(type), file, UploadVideoExt, UploadFlashSize, out msg);
                case 6:
                    return SaveFile(GetTypeByEn(type), file, UploadPPTExt, UploadFlashSize, out msg);
                case 7:
                    return SaveFile(GetTypeByEn(type), file, UploadLinkExt, UploadLinkSize, out msg);
            }
            msg = "类型错误.";
            return "";
        }

        public static bool IsMatchSize(HttpPostedFileBase file, int max)
        {
            if (file.ContentLength > max * 1000)
            {
                return false;
            }
            return true;
        }

        public static string GetFileExt(string fullPath)
        {
            if (fullPath != "") return fullPath.Substring(fullPath.LastIndexOf('.') + 1).ToLower();
            else return "";
        }

        public static void DeleteFile(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return;
            System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/") + fileName);
        }

        public static string SaveFile(string typeName, HttpPostedFileBase file, string uploadExts, int maxSize, out string msg)
        {
            msg = "";
            if (file == null || file.ContentLength == 0)
                return "";
            string testExt = GetFileExt(file.FileName);
            if (string.IsNullOrEmpty(testExt))
            {
                msg = "后缀名获取失败!";
                return "";
            }
            if (!uploadExts.Contains(testExt))
            {
                msg = "上传格式必须为:" + uploadExts;
                return "";
            }
            var ext = "." + testExt;
            if (!IsMatchSize(file, maxSize))
            {
                msg = "不能上传超过" + maxSize + "K的文件.";
                return "";
            }
            string filePath = HttpContext.Current.Server.MapPath("~/Upload/Res/" + typeName + "/");
            string time = DateTime.Now.ToString("yyyy/MM/dd/").Replace('-', '/');
            if (!Directory.Exists(filePath + time))
                Directory.CreateDirectory(filePath + time);

            string tempSrc = DateTime.Now.ToString("hhmmssfff") + ext;
            while (File.Exists(filePath + time + tempSrc))
            {
                tempSrc = DateTime.Now.ToString("hhmmssfff") + ext;
            }
            var fileName = filePath + time + tempSrc;
            file.SaveAs(fileName);
            return "Upload/Res/" + typeName + "/" + time + tempSrc;
        }

        public static string GetTypeByEn(byte type)
        {
            switch (type)
            {
                case 1:
                    return "Text";
                case 2:
                    return "Img";
                case 3:
                    return "Flash";
                case 4:
                    return "Sound";
                case 5:
                    return "Video";
                case 6:
                    return "PPT";
                case 7:
                    return "Package";
            }
            return "NotFound";
        }

        public static string GetTypeByChs(byte type)
        {
            switch (type)
            {
                case 1:
                    return "文本";
                case 2:
                    return "图像";
                case 3:
                    return "Flash";
                case 4:
                    return "音频";
                case 5:
                    return "视频";
                case 6:
                    return "PPT";
                case 7:
                    return "学习包";
            }
            return "NotFound";
        }
    }
}
